<template>
  <div>
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="password"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="password.oldPassword" type="password" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="password.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认新密码" prop="passwordConfirmation">
        <el-input v-model="password.passwordConfirmation" type="password" placeholder="确认新密码" />
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="submit">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { changePwd } from '@/api/user'
const _temp = {
  oldPassword: '',
  newPassword: '',
  passwordConfirmation: ''
}
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.password.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      showPassword: true,
      showPasswordAgain: true,
      password: Object.assign({}, _temp),
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码' },
          { pattern: '(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,16}', message: '8-16位, 必须包含数字、字母、特殊字符' }
        ],
        passwordConfirmation: [
          { required: true, validator: validatePass2 }
        ]
      }
    }
  },
  methods: {
    resetTemp() {
      this.password = Object.assign({}, _temp)
    },
    changePwdEvent() {
      this.resetTemp()
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    submit() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.save()
        }
      })
    },
    save() {
      this.loading = true
      changePwd(this.password).then(res => {
        this.$message({
          message: res.errmsg,
          type: 'success'
        })
        this.loading = false
        setTimeout(async() => {
          await this.$store.dispatch('user/logout')
          this.$router.push(`/login?redirect=${this.$route.fullPath}`)
        }, 300)
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

